package com.trw.trp;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.FilterConfig;
import javax.servlet.ServletException;

import org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter;

import com.trw.trp.dao.DaoFactory;
import com.trw.trp.dao.OrderDao;
import com.utuan.log.Log;
import com.utuan.log.LogFactory;

public class TRPServletFilter extends StrutsPrepareAndExecuteFilter {
	private static Log log = LogFactory.getLog(TRPServletFilter.class);

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		super.init(arg0);
		//startService();
	}

	private void startService() {
		log.debug("entering startService..");
		Timer timer = new Timer(true);
		Calendar cal = new GregorianCalendar();
		cal.setTime(new Date());
		long period = 1000 * 60 * 60 * 24;
		final OrderDao dao = DaoFactory.getOrderDao();
		dao.autoCompleteOrder();
		timer.scheduleAtFixedRate(new TimerTask() {
			@Override
			public void run() {
				dao.autoCompleteOrder();
			}
		}, getStartDay(), period);
		
		log.debug("exiting startService..");
	}

	private Date getStartDay() {
		Calendar cal = new GregorianCalendar();
		cal.setTime(new Date());
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		cal.add(Calendar.DAY_OF_MONTH, 1);
		return cal.getTime();
	}

}
